﻿using Business;
using Common;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PayService.JieBao
{
    public class JBHttpHelper
    {
        public static httpModel PostAddMoney(string userName, decimal Amount, string cookie,string order_no)
        {
            httpModel result = new httpModel() { status = DoResult.Success };

            string PostMoneyUrl = "http://cszhun.67430000.com/ArtificialOp/Receivables/addpost";
            StringBuilder sb = new StringBuilder();
            decimal AuditAmount = Convert.ToDecimal((Amount / 3).ToString("F2"));//打码量
            //sb.Append("?savetype=" + 318);//操作项目类型，人工存入
            //sb.Append("&dps_amount=" + Amount);//充值金额 
            //sb.Append("&dps_bet_amount=" + AuditAmount);//打码量
            //sb.Append("&dps_note=" + "自动入款");//备注
            //sb.Append("&account[]=" + userName); //账号[]
            string postData = $"savetype=318&dps_amount={Amount}&dps_bet_amount={AuditAmount}&dps_note=Auto&account%5B%5D={userName}";
            string resultStr = CallHtmlForm(PostMoneyUrl, cookie, postData);
            try
            {//解析html判断是否入款成功
                var docText = resultStr;
                //加载源代码，获取文档对象
                var doc = new HtmlDocument();
                doc.LoadHtml(docText);
                //更加xpath获取总的对象，如果不为空，就继续选择dl标签
                var res = doc.DocumentNode.SelectSingleNode("//table");
                //获取返回的html查询用户充值列表第一个是否为当前入款账户
                string FirstUsername = doc.DocumentNode.SelectSingleNode("//tbody").ChildNodes["tr"].SelectNodes("td")[1].InnerText;
                if (FirstUsername == userName)
                {//此处有bug，如果紧接着上次用户也有充值记录一样的价格，这次没有成功也会提示成功。
                    string str = $"用户【{userName}】；充值金额【{Amount}】；单号【{order_no}】；状态【入款成功】；";
                    result.status = DoResult.Success;
                    result.msg = str;
                }
                else
                {
                    result.status = DoResult.Failed;
                    result.msg = $"用户【{userName}】；充值金额【{Amount}】；单号【{order_no}】；状态【入款失败（解析返回HTML用户列表第一个与入款账户不相符），请联系管理员，】";
                }
            }
            catch (Exception ex)
            {
                result.status = DoResult.Failed;
                result.msg = $"用户【{userName}】；充值金额【{Amount}】；单号【{order_no}】；状态【入款失败（解析返回HTML失败，可能是cookie失效），请联系管理员，】";
            }
            return result;
        }
        public static string CallHtmlForm(string URL, string cookie, string postData)
        {
            HttpWebRequest request = HttpWebRequest.Create(URL) as HttpWebRequest;
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36";
            request.Method = "POST";
            request.Headers.Add("Cookie", cookie);
            request.Host = "cszhun.67430000.com";
            request.Referer = "http://cszhun.67430000.com/ArtificialOp/Receivables/srcacc";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Proxy = null;
            request.AllowAutoRedirect = true;
            request.Headers.Add("Origin", "http://cszhun.67430000.com");
            //转换输入参数的编码类型，获取bytep[]数组 
            WebResponse response;
            ////整数据  
            //string postData = "srcacc=jx100866";

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] bytepostData = encoding.GetBytes(postData);
            request.ContentLength = bytepostData.Length;

            //发送数据  using结束代码段释放
            using (Stream requestStm = request.GetRequestStream())
            {
                requestStm.Write(bytepostData, 0, bytepostData.Length);
            }

            response = request.GetResponse();
            string reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            try
            {
                request.GetResponse().Close();
            }
            catch (WebException ex)
            {
                LogHelper.Error("请求页面的时候出错：" + ex.Message);
                throw ex;
            }
            return reader;
        }
    }
}
